package com.blockchain.anti_counterfeiting.api;

import com.blockchain.anti_counterfeiting.auth.Auth;
import com.blockchain.user.User;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;


@WebServlet(urlPatterns = "/tologin")
public class Login extends HttpServlet {
    public String email;
    private String password;
    private JsonNode person;


    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        PrintWriter out = res.getWriter();
        req.setCharacterEncoding("UTF-8");
        res.setContentType("Application/json");
//        res.setContentType("text/html");
        try {
            this.email = req.getParameter("username");
            this.password = String.valueOf(req.getParameter("password").hashCode());

            User user = new User(getEmail());

            this.person = user.users();
            if (password.equals(user.getPassword())) {
                Auth a = new Auth(user.getUid(),password);
                user.addToken(a.generateToken());
                user.dropThings(user.getPassword());
                user.dropThings(user.getPhone());
                out.println(person.toString());
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (RuntimeException | SQLException | ClassNotFoundException e) {
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
//            throw new RuntimeException(e);
        }
        destroy();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }
}
